import { Ref, unref } from 'vue'
import { useEventListener } from './useEventListener'

export type UserClickAwayOptions = {
	eventName?: string
}

export const isBrowser = typeof window !== 'undefined'

export function useClickAway(
	target: Element | Ref<Element | undefined>,
	listener: EventListener,
	optionos: UserClickAwayOptions
) {
	if (!isBrowser) return

	const { eventName = 'click' } = optionos

	const onClick = (event: Event) => {
		const element = unref(target)
		if (element && !element.contains(event.target as Node)) {
			listener(event)
		}
	}

	useEventListener(eventName, onClick, { target: document })
}
